<template>
  <div class="custom-table">
    <!-- 顶部操作栏 -->
    <div class="header-section">
      <h3>查验项目</h3>
      <div class="action-buttons" v-if="isEditable">
        <span style="color: #e37318; margin-right: 10px"
          >费用：￥{{ TotalCost }}</span
        >
        <div class="line"></div>
        <el-button
          type="primary"
          plain
          @click="setActiveType('1')"
          :disabled="!isEditable"
        >
          检查
        </el-button>
        <el-button
          type="primary"
          plain
          @click="setActiveType('2')"
          :disabled="!isEditable"
        >
          检验
        </el-button>
        <div class="line" style="margin-left: 10px"></div>
        <el-button plain @click="onSelectTemplate" :disabled="!isEditable">
          选择模板
        </el-button>
        <el-button plain @click="onSave()" :disabled="!isEditable">
          存模板
        </el-button>
      </div>
    </div>
    <!-- 表头 -->
    <div class="table-header">
      <div
        v-for="column in props.columns"
        :key="column.key"
        class="header-cell"
        :style="{
          width: column.flex ? undefined : column.width,
          flex: column.flex ? 1 : undefined,
          textAlign: column.align || 'left',
        }"
      >
        {{ column.label }}
      </div>
    </div>

    <!-- 表格数据行 -->
    <div
      v-for="(row, index) in displayTableData"
      :key="row.uuid"
      class="table-row-container"
      :class="{ 'add-row': row.isNew }"
    >
      <div class="table-row" :class="{ 'add-row': row.isNew }">
        <div
          v-for="column in props.columns"
          :key="column.key"
          class="table-cell"
          :style="getColumnStyle(column)"
        >
          <!-- 序号列 -->
          <template v-if="column.key === 'index'">
            {{ row.isNew ? '' : index + 1 }}
          </template>

          <!-- 项目列 -->
          <template v-else-if="column.key === 'name'">
            <span>{{ row.projectName }}</span>
          </template>

          <!-- 类别列 -->
          <template v-else-if="column.key === 'category'">
            {{ row.projectCategoryName }}
          </template>

          <!-- 频率列 -->
          <template v-else-if="column.key === 'frequency'">
            <!-- <el-select
              v-model="row.frequencyCode"
              filterable
              style="width: 100px"
              class="borderless-select"
              suffix-icon=""
              @change="onFrequency(row, index)"
              v-if="isEditable"
            >
              <el-option
                v-for="frequency in frequencyOptions"
                :key="frequency.frequencyCode"
                :label="frequency.frequencyName"
                :value="frequency.frequencyCode"
              />
            </el-select> -->
            <el-select
              v-model="row.frequencyCode"
              style="width: 100px"
              filterable
              class="borderless-select"
              suffix-icon=""
              @focus="onfrequency"
              v-if="isEditable && row.payStatus != '2'"
              @change="onFrequency(row, index)"
            >
              <el-option
                v-for="frequency in frequency"
                :key="frequency.frequencyCode"
                :label="frequency.frequencyName"
                :value="frequency.frequencyCode"
                style="padding: 0 8px"
              >
                <span style="float: left">{{ frequency.frequencyCode }}</span>
                <span style="float: right; font-size: 13px">
                  {{ frequency.frequencyName }}
                </span>
              </el-option>
            </el-select>
            <span v-else>{{ row.frequencyCodeText }}</span>
          </template>

          <!-- 周期列 -->
          <template v-else-if="column.key === 'cycle'">
            <div
              style="
                display: flex;
                align-items: center;
                gap: 8px;
                position: relative;
              "
            >
              <el-input-number
                v-model="row.cycle"
                :min="1"
                :max="999"
                :controls="false"
                class="borderless-input"
                style="width: 50px"
                @change="updateRow(row, index, 'cycle')"
                @focus="showKeyboard(row, index, 'cycle')"
                @click.stop
                v-if="isEditable && row.payStatus != '2'"
              />
              <span v-else>{{ row.cycle }}</span>
              <span>{{ row.cycleUnitText }}</span>

              <!-- 数字键盘 -->
              <div
                v-if="
                  keyboardVisible &&
                  currentEditRow === row &&
                  currentEditField === 'cycle'
                "
                class="number-keyboard"
                @click.stop
              >
                <NumericKeyboardInt
                  @input="inputNumber"
                  @delete="deleteNumber"
                />
              </div>
            </div>
          </template>

          <!-- 总量列 -->
          <template v-else-if="column.key === 'totalCount'">
            <div
              style="
                display: flex;
                align-items: center;
                gap: 4px;
                position: relative;
              "
            >
              <el-input-number
                v-model="row.totalOutQty"
                :min="0"
                :max="999"
                :controls="false"
                class="borderless-input"
                ref="searchInputRef"
                style="width: 50px"
                @change="updateRow(row, index)"
                @focus="showKeyboard(row, index, 'totalOutQty')"
                @click.stop
                v-if="isEditable && row.payStatus != '2'"
              />
              <span v-else>{{ row.totalOutQty }}</span>
              <div>{{ row.totalOutQtyUnitText || ' ' }}</div>

              <!-- 总量数字键盘 -->
              <div
                v-if="
                  keyboardVisible &&
                  currentEditRow === row &&
                  currentEditField === 'totalOutQty'
                "
                class="number-keyboard"
                @click.stop
              >
                <NumericKeyboardInt
                  @input="inputNumber"
                  @delete="deleteNumber"
                />
              </div>
            </div>
          </template>

          <!-- 备注列 -->
          <template v-else-if="column.key === 'remark'">
            <!-- <el-input
              v-model="row.remark"
              style="width: calc(100% - 30px)"
              class="no-border-input"
              placeholder="请输入备注"
              @change="updateRow(row, index)"
              v-if="props.activeName_1 != '2'"
            />
            <span v-else>{{ row.remark }}</span>
            <el-button
              v-if="row.isNew"
              type="primary"
              text
              size="small"
              style="margin-left: 8px"
              @click="confirmAdd(row, index)"
            >
              +
            </el-button> -->

            <!-- <el-autocomplete
              v-model="row.remark"
              class="borderless-select right-select"
              placeholder=""
              :trigger-on-focus="true"
              :fetch-suggestions="querySearchAsync"
              :disabled="!isEditable"
            >
            </el-autocomplete> -->
            <AutocompleteMulti
              v-model="row.remark"
              class="borderless-select right-select"
              placeholder=""
              style="width: calc(100% - 30px)"
              :trigger-on-focus="true"
              :fetch-suggestions="querySearchAsync"
              :selected-color="'#16ada4'"
              v-if="isEditable && row.payStatus != '2'"
            />
            <span v-else>{{ row.remark }}</span>
          </template>

          <!-- 自定义列 -->
          <template v-else>
            {{ row[column.key as keyof any] }}
          </template>
        </div>
      </div>

      <!-- 悬浮删除按钮 -->
      <div class="delete-button-1" v-if="isEditable && row.payStatus != '2'">
        <div class="delete-button" @click="deleteRow(row, index)">
          <img src="@/assets/manage/icon_off_hover.svg" alt="删除" />
        </div>
      </div>
    </div>
    <!-- 搜索行 -->
    <div class="table-row search-row" v-if="isEditable">
      <div
        v-for="(column, columnIndex) in props.columns"
        :key="`search-${column.key}`"
        class="table-cell"
        :style="{
          border: columnIndex === 0 ? 'none' : undefined,
          position: columnIndex === 0 ? 'relative' : undefined,
        }"
      >
        <template v-if="columnIndex === 0">
          <div
            class="table-row"
            style="font-size: 16px; color: #999999; line-height: 50px"
          >
            +
          </div>
          <el-input
            v-model="searchText"
            placeholder="搜索项目名称或拼音缩写"
            class="search-input2"
            style="width: 100%"
            clearable
            @input="handleSearch"
            @focus="showSearchKeyboard"
            @click.stop
          />

          <!-- 搜索全键盘 -->
          <div v-if="searchKeyboardVisible && isEditable" class="" @click.stop>
            <!-- 数字行 (所有模式都显示) -->
            <SearchKeyboard
              :mode="keyboardMode"
              @input="(result: any) => inputSearchChar(result)"
              @delete="deleteSearchChar()"
              @clear="clearSearch"
              @switch="switchKeyboard"
              v-if="searchKeyboardVisible"
            />
          </div>

          <!-- 搜索结果下拉列表 -->
          <div
            v-if="searchResults.length > 0 && isEditable"
            class="search-results2"
            @click.stop
          >
            <div class="table-header">
              <div
                class="header-cell"
                style="width: 620px; text-align: left; padding-left: 16px"
              >
                项目
              </div>
              <div
                class="header-cell"
                style="width: 100px; text-align: left; padding-left: 16px"
              >
                类别
              </div>
              <div
                class="header-cell"
                style="width: 100px; text-align: left; padding-left: 16px"
              >
                规格
              </div>
              <div
                class="header-cell"
                style="width: 100px; text-align: left; padding-left: 16px"
              >
                单价
              </div>
            </div>
            <div
              v-for="result in searchResults"
              :key="result.projectId"
              class="search-result-item"
              @click="selectSearchResult(result)"
            >
              <div
                class="result-name"
                style="width: 620px; text-align: left; padding-left: 16px"
              >
                {{ result.projectName }}
              </div>
              <div
                class="result-category"
                style="width: 100px; text-align: left; padding-left: 16px"
              >
                {{ result.projectCategoryName }}
              </div>
              <div
                class="result-spec"
                style="width: 100px; text-align: left; padding-left: 16px"
              >
                {{ result.unitName }}
              </div>
              <div
                class="result-price"
                style="width: 100px; text-align: left; padding-left: 16px"
              >
                ¥ {{ (result.price / 100).toFixed(2) }}
              </div>
            </div>
          </div>
        </template>
      </div>
    </div>
    <!-- 检验 -->
    <div>
      <el-dialog
        v-model="dialogVisible"
        class="custom-transition-dialog"
        width="50%"
      >
        <Examine
          :activeType="activeType"
          :tableData="tableData"
          :frequencyOptions="frequency"
          @updateRow="updateRow"
          @close="onCloseExamine"
          @confirm="handleExamineConfirm"
          ref="examineRef"
        />
      </el-dialog>
    </div>
    <!-- 选择模板 -->
    <el-dialog
      v-model="isTemplate"
      class="custom-transition-dialog-1"
      :title="''"
      :width="1200"
      top="5vh"
      @close="isTemplate = false"
    >
      <template #header="{ close, titleId, titleClass }" style="display: none">
        <div class="my-header" style="display: none">
          <el-icon class="el-icon--left"><CircleCloseFilled /></el-icon>
        </div>
      </template>
      <!-- 1是病历模板 2是检验模板 3是处方模板 -->
      <managePages
        :activeName_s="'2'"
        v-if="isTemplate"
        :medicalList="displayTableData"
        @updataTemplate="updataTemplate"
      />
    </el-dialog>
    <addTemplate ref="addTemplateRef" @addTemplate="onAddTemplate">
    </addTemplate>
  </div>
</template>

<script lang="ts" setup>
import { CircleCloseFilled } from '@element-plus/icons-vue';
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { ElMessage } from 'element-plus';
import { getFeeStandardList, addTemplateInspection } from '@/api/formwork';
import addTemplate from './addTemplate.vue';
import managePages from './managePages.vue';
import stores from '@/store';
import { v4 as uuidv4 } from 'uuid';
const useBaseDataStore = stores.useBaseDataStore();
const cycleUnitEnum = ref(useBaseDataStore.getEnumSelect('cycleUnitEnum'));
const frequency = ref(useBaseDataStore.getDictsSelect('FREQUENCY'));
const searchKeyboardOnTop = ref(false);
const searchInputRef = ref<HTMLInputElement | null>(null);
const dialogVisible = ref(false);
const isTemplate = ref(false);
const TotalCost = ref('0.00'); //费用
const addTemplateRef = ref<InstanceType<typeof addTemplate> | null>(null);
const examineRef = ref<any>(null);
// 定义数据类型
// interface any {
//   examId: number;
//   projectId: number; // 主键ID
//   projectName: string; // 项目名称;CT
//   price: number; // 价格
//   projectCategory: string; // 项目分类;1检查2.检验3.治疗 projectCategoryEnum
//   projectCategoryName: string; // 项目分类名称
//   projectType: string; // 项目类型;头部CT 如果projectCategory=1取字典中的EXAM_TYPE,projectCategory=2取LAB_TYPE，如果等于3取EXT_TYPE
//   sampleType: string; // 样本类型;如果是检验项目需要维护1.全血 sampleTypeEnum
//   chargeType: string; // 收费类型1项目2穴位 ProjectChargeTypeEnum
//   unit: string; // 单位;次 取字典接口中key=UNIT并且unitType=2的数据
//   unitName: string; // 单位;次 取字典接口中key=UNIT并且unitType=2的数据
//   isNew?: boolean;
//   remark?: string;
//   frequencyCode?: string; // 频率代码
//   frequencyName?: string; // 频率名称
// }

// 定义表头列类型
interface TableColumn {
  key: string;
  label: string;
  width?: string;
  flex?: boolean;
  align?: 'left' | 'center' | 'right';
  justifyContent?: 'center' | '';
}

// Props
interface Props {
  title?: string;
  tableData?: any[];
  frequencyOptions?: any[];
  defaultActiveType?: string;
  columns?: TableColumn[];
  fieldList?: any[];
  visitStatus?: string;
  onZS?: any;
}

const props = withDefaults(defineProps<Props>(), {
  title: '查验项目',
  tableData: () => [],
  frequencyOptions: () => [],
  defaultActiveType: '1',
  fieldList: () => [],
  visitStatus: '2',
  onZS: () => '',
  columns: () => [
    {
      key: 'index',
      label: '序号',
      width: '80px',
      align: 'center',
      justifyContent: 'center',
    },
    { key: 'name', label: '项目', width: '150px' },
    { key: 'category', label: '类别', width: '109px' },
    { key: 'frequency', label: '频率', width: '140px' },
    { key: 'cycle', label: '周期', width: '130px' },
    { key: 'totalCount', label: '总量', width: '100px' },
    { key: 'priceNum', label: '单价', width: '100px' },
    { key: 'subtotalNum', label: '金额', width: '100px' },
    { key: 'remark', label: '备注', flex: true },
  ],
});

// Emits
const emit = defineEmits<{
  'update:tableData': [value: any[]];
  'active-type-change': [type: 'inspection' | 'examination'];
  'row-update': [row: any, index: number];
  'search-result-select': [result: any];
}>();

// 响应式数据
const activeType = ref<any>(props.defaultActiveType);
const searchText = ref('');
const searchKeyboardVisible = ref(false);
const keyboardMode = ref<'english' | 'chinese'>('english');
const searchResults = ref<any[]>([]);
const isEditable = computed(() => props.visitStatus === '1');

// 数字键盘相关
const keyboardVisible = ref(false);
const currentEditRow = ref<any | null>(null);
const currentEditField = ref<'cycle' | 'totalOutQty' | null>(null);

// 获取列的样式
const getColumnStyle = (column: TableColumn) => {
  return {
    width: column.flex ? undefined : column.width,
    flex: column.flex ? 1 : undefined,
    textAlign: column.align || 'left',
    justifyContent: column.justifyContent || '',
  };
};
const displayTableData = ref<any[]>([]);
// 计算属性：过滤后的表格数据
watch(
  () => props.tableData,
  (newVal) => {
    displayTableData.value = newVal.map((item) => ({
      ...item,
      projectCategoryName: useBaseDataStore.getEnumData(
        item.projectCategory,
        'projectCategoryEnum'
      ),
      priceNum:
        item?.price !== undefined && item?.price !== null
          ? (Number(item.price) / 100).toFixed(2)
          : '0.00', // 保留两位小数
      subtotalNum: '￥' + (Number(item?.subtotal ?? 0) / 100).toFixed(2),
      cycleUnitText: useBaseDataStore.getEnumData(
        item.cycleUnit,
        'cycleUnitEnum'
      ),
      frequencyTimes: frequency.value?.find(
        (freq: { frequencyCode: any }) =>
          freq.frequencyCode === item.frequencyCode
      )?.frequencyTimes,
      totalOutQtyUnitText: useBaseDataStore.getDictsData(
        item.totalOutQtyUnit,
        'UNIT'
      ),
      uuid: uuidv4(), // 唯一标识
    }));
    // 累计总费用：单价(分) * 数量，再转为元两位小数
    const totalCents = newVal.reduce(
      (acc, cur) =>
        acc + (Number(cur.price) || 0) * (Number(cur.totalOutQty) || 0),
      0
    );
    TotalCost.value = (totalCents / 100).toFixed(2);
  },
  { immediate: true }
);
// 深度差异比较函数
function getDeepChanges(newObj: any[], oldObj: any[], path = '') {
  if (!oldObj) return [{ path, newValue: newObj }];

  if (Array.isArray(newObj)) {
    const changes: any[] = [];
    newObj.forEach((item, index) => {
      changes.push(...getDeepChanges(item, oldObj[index], `${path}[${index}]`));
    });
    return changes;
  }

  return newObj !== oldObj
    ? [{ path, oldValue: oldObj, newValue: newObj }]
    : [];
}
function extractDifferences(changeItems: any[]) {
  // 深度比较两个值是否相等
  function isDeepEqual(
    a: { [x: string]: any } | null,
    b: { [x: string]: any } | null
  ) {
    if (a === b) return true;
    if (
      typeof a !== 'object' ||
      a === null ||
      typeof b !== 'object' ||
      b === null
    )
      return false;

    const keysA = Object.keys(a);
    const keysB = Object.keys(b);
    if (keysA.length !== keysB.length) return false;

    for (const key of keysA) {
      if (!keysB.includes(key)) return false;
      if (!isDeepEqual(a[key], b[key])) return false;
    }
    return true;
  }

  return changeItems
    .map((item) => {
      const { path, oldValue, newValue } = item;
      const uuid = newValue?.uuid || oldValue?.uuid; // 获取UUID

      const changedFields: any = {};

      // 收集所有key，包括oldValue和newValue中的
      const allKeys = new Set([
        ...Object.keys(oldValue || {}),
        ...Object.keys(newValue || {}),
      ]);

      // 比较每个字段
      for (const key of allKeys) {
        const oldVal = oldValue?.[key];
        const newVal = newValue?.[key];
        // 只有当值确实不同时才记录
        if (!isDeepEqual(oldVal, newVal)) {
          changedFields[key] = {
            old: oldVal,
            new: newVal,
            uuid: uuid,
          };
        }
      }

      // 只返回有实际变化的项
      return Object.keys(changedFields).length > 0
        ? { path, changes: changedFields, uuid }
        : null;
    })
    .filter(Boolean); // 过滤掉没有实际变化的项
}
watch(
  () =>
    displayTableData.value.map(
      (drug: {
        totalOutQty: any;
        frequencyCode: any;
        cycle: any;
        uuid: any;
      }) => ({
        cycle: drug.cycle,
        frequencyCode: drug.frequencyCode,
        uuid: drug.uuid,
        totalOutQty: drug.totalOutQty,
      })
    ),
  (newSnap, oldSnap) => {
    //console.log(newSnap);
    //console.log(oldSnap);
    const diffs = extractDifferences(getDeepChanges(newSnap, oldSnap));
    //console.log('实际变化的字段:', diffs);
    const changedUUIDs = diffs.map((diff: any) => diff.uuid).filter(Boolean);

    // 仅当上述字段发生变化时触发
    const totalCents = displayTableData.value.reduce(
      (acc, cur) =>
        acc + (Number(cur.price) || 0) * (Number(cur.totalOutQty) || 0),
      0
    );
    console.log(currentEditField.value);
    
    displayTableData.value.forEach((item) => {
      if (
        currentEditField.value == 'cycle' &&
        changedUUIDs.includes(item.uuid)
      ) {
        if (item.cycle) {
          item.totalOutQty = item.cycle * item.frequencyTimes;
        } else {
          item.totalOutQty = null;
        }
      }
      if (item.cycle) {
        item.subtotalNum =
          '￥' + (Number(item?.price * item.totalOutQty) / 100).toFixed(2);
      } else {
        item.subtotalNum = '￥0.00';
      }
    });
    // displayTableData.value = displayTableData.value.map((item) => ({
    //   ...item,
    //   subtotalNum: '￥' + (Number(item?.price * (item?.cycle=='' || item.cycle==null ? '1' : item.cycle)) / 100).toFixed(2),
    // }));
    TotalCost.value = (totalCents / 100).toFixed(2);
  }
);
// 方法
const setActiveType = (type: string) => {
  if (!isEditable.value) return;
  activeType.value = type;
  dialogVisible.value = true;
  nextTick(() => {
    if (examineRef.value) {
      // examineRef.value.onreset();
    }
  });
};
const updataTemplate = (templates: any) => {
  //console.log(templates);
  isTemplate.value = false;
  let detailList = [];
  detailList = templates.detailList.map((item: any) => ({
    ...item,
    projectCategoryName: useBaseDataStore.getEnumData(
      item.projectCategory,
      'projectCategoryEnum'
    ),
    priceNum:
      item?.price !== undefined && item?.price !== null
        ? (Number(item.price) / 100).toFixed(2)
        : '0.00', // 保留两位小数
    subtotalNum:
      '￥' +
      (
        Number(
          item?.price *
            (item?.cycle == '' || item.cycle == null ? '1' : item.cycle)
        ) / 100
      ).toFixed(2),
    cycleUnit:
      item?.cycleUnit == '' || item.cycleUnit == null ? 'day' : item.cycleUnit,

    cycleUnitText: useBaseDataStore.getEnumData(
      item?.cycleUnit == '' || item.cycleUnit == null ? 'day' : item.cycleUnit,
      'cycleUnitEnum'
    ),

    frequencyTimes: frequency.value?.find(
      (freq: { frequencyCode: any }) =>
        freq.frequencyCode ===
        (item?.frequencyCode == '' || item.frequencyCode == null
          ? 'qd'
          : item.frequencyCode)
    )?.frequencyTimes,
    totalOutQty:
      item?.totalOutQty == '' || item.totalOutQty == null
        ? '1'
        : item.totalOutQty,
    cycle: item?.cycle == '' || item.cycle == null ? '1' : item.cycle,
    frequencyCode:
      item?.frequencyCode == '' || item.frequencyCode == null
        ? 'qd'
        : item.frequencyCode,

    totalOutQtyUnitText: useBaseDataStore.getDictsData(
      item.totalOutQtyUnit,
      'UNIT'
    ),
  }));
  detailList.forEach((item: any) => {
    //console.log(item);
    delete item.examId;
    item.uuid = uuidv4();
    displayTableData.value.push(item);
  });
};
const updateRow = (row: any, index: number, type?: string) => {
  //console.log('updateRow called:', { row, index, type });
  //console.log('Row data:', JSON.stringify(row, null, 2));

  if (type) {
    row.totalOutQty = row.cycle * row.frequencyTimes;
    const price = Number(row.price) || 0;
    const qty = Number(row.totalOutQty) || 0;
    row.subtotal = price * qty;
    row.subtotalNum = '￥' + (row.subtotal / 100).toFixed(2);
    emit('row-update', row, index);
  } else {
    // row.totalOutQty = row.cycle * row.frequencyTimes;
    const price = Number(row.price) || 0;
    const qty = Number(row.totalOutQty) || 0;
    row.subtotal = price * qty;
    row.subtotalNum = '￥' + (row.subtotal / 100).toFixed(2);
    emit('row-update', row, index);
  }
};
const onFrequency = (row: any, index: number) => {
  const selectedFrequency = props.frequencyOptions?.find(
    (freq) => freq.frequencyCode === row.frequencyCode
  );
  if (selectedFrequency) {
    row.frequencyTimes = selectedFrequency.frequencyTimes;
    row.cycleUnit = selectedFrequency.cycleUnit;
    row.totalOutQty = row.cycle * row.frequencyTimes;
    (row.cycleUnitText = useBaseDataStore.getEnumData(
      selectedFrequency.cycleUnit,
      'cycleUnitEnum'
    )),
      updateRow(row, index);
  }
};
const onCloseExamine = () => {
  dialogVisible.value = false;
  activeType.value = '';
};
// 获取单位名称的方法
const getUnitName = (unitCode: string) => {
  const UNITDATA = useBaseDataStore.getDictsSelect('UNIT') || [];
  // 过滤出unitType等于2的数据
  const filteredUnits = UNITDATA.filter(
    (unit: any) => unit.unitType === '2' || unit.unitType === 2
  );
  // 根据unitCode查找对应的单位名称
  const foundUnit = filteredUnits.find(
    (unit: any) => unit.unitCode === unitCode
  );
  //console.log(foundUnit);

  return foundUnit ? foundUnit.unitText : unitCode; // 如果找不到就返回原始unitCode
};
// 选择模板
const onSelectTemplate = () => {
  if (!isEditable.value) return;
  isTemplate.value = true;
};
// 搜索方法
const handleSearch = async (value: string) => {
  //console.log('搜索内容:', value);
  //console.log(props.onZS());
  // 调用API获取搜索结果数据

  // 将props.onZS()返回值中的中文逗号替换为英文逗号
  const zsValue = props.onZS()?.replace(/，/g, ',') || '';
  const result = await getFeeStandardList({
    projectName: value,
    recoms: zsValue,
  });
  if (result.code != '200') {
    //ElMessage.error(result.msg);
    return;
  }
  searchResults.value =
    result?.data.map((item: any) => ({
      projectId: item.projectId,
      projectName: item.projectName,
      price: item.price,
      projectCategory: item.projectCategory,
      projectCategoryName: useBaseDataStore.getEnumData(
        item.projectCategory,
        'projectCategoryEnum'
      ),
      projectType: item.projectType,
      sampleType: item.sampleType || '',
      chargeType: item.chargeType,
      unit: item.unit,
      unitName: getUnitName(item.unit), // 使用新的方法获取单位名称
      priceNum:
        item?.price !== undefined && item?.price !== null
          ? (Number(item.price) / 100).toFixed(2)
          : '0.00',
    })) || [];
};
const onSave = () => {
  const type = {
    templateCategory: '2', // 1病历 2检验 3处方
    templateType: '1',
  };
  addTemplateRef.value?.open1(type);
};
const querySearchAsync = (queryString: string, cb: any) => {
  const data1 = useBaseDataStore.getDictsSelect('REMARK') || [];
  // 仅保留 rxType 为 5 的项（兼容数字/字符串）
  const filtered = (Array.isArray(data1) ? data1 : []).filter(
    (item: any) => item?.rxType === 5 || item?.rxType === '5'
  );
  const results = filtered.map((item: any) => ({
    value: item.remarkText,
    ...item,
  }));
  cb(results);
};
// 获取病历字段
const settingsCheckList = (value: any, newFormat: string) => {
  // newFormatType.value = newFormat;
};
// 搜索键盘相关方法
const showSearchKeyboard = () => {
  if (!isEditable.value) return;
  searchKeyboardVisible.value = true;
  keyboardVisible.value = false;
  document.addEventListener('keydown', handleKeyboardShortcut);
  handleSearch('');
};
const onfrequency = () => {
  // showMedicationTabs.value = false;
  keyboardVisible.value = false;
  searchKeyboardVisible.value = false;
  searchResults.value = [];
};
// 保存模板
const onAddTemplate = async (data: any) => {
  //console.log('保存模板数据:', data);
  const examList = displayTableData.value.map(
    (item: {
      projectId: any;
      frequencyCode: any;
      cycle: any;
      remark: any;
      totalOutQty: any;
    }) => {
      return {
        projectId: item.projectId,
        frequencyCode: item.frequencyCode,
        cycle: item.cycle,
        remark: item.remark,
        totalOutQty: item.totalOutQty,
      };
    }
  );
  const data1 = {
    ...data,
    recomScene: '',
    examList: examList,
  };
  const result = await addTemplateInspection(data1);
  if (result.code != '200') {
    //ElMessage.error(result.msg);
    return;
  }
  if (
    addTemplateRef.value &&
    typeof addTemplateRef.value.onclose === 'function'
  ) {
    addTemplateRef.value.onclose();
  }
  ElMessage.success('模板保存成功');
};
const hideSearchKeyboard = (event?: Event) => {
  if (event && event.target) {
    const target = event.target as Element;
    if (
      target.closest('.search-keyboard') ||
      target.closest('.search-results2') ||
      target.closest('.search-input2')
    ) {
      return;
    }
  }

  searchKeyboardVisible.value = false;
  searchResults.value = [];
  document.removeEventListener('keydown', handleKeyboardShortcut);
};

const handleKeyboardShortcut = (event: KeyboardEvent) => {
  if (event.ctrlKey && event.shiftKey && event.key === 'T') {
    event.preventDefault();
    switchKeyboard();
  } else if (event.key === 'Escape') {
    event.preventDefault();
    hideSearchKeyboard();
  }
};

const inputSearchChar = (char: string) => {
  searchText.value += char;
  handleSearch(searchText.value);
};

const deleteSearchChar = () => {
  if (searchText.value.length > 0) {
    searchText.value = searchText.value.slice(0, -1);
    handleSearch(searchText.value);
  }
};

const clearSearch = () => {
  searchText.value = '';
  searchResults.value = [];
};

const switchKeyboard = () => {
  if (keyboardMode.value === 'english') {
    keyboardMode.value = 'chinese';
  } else if (keyboardMode.value === 'chinese') {
    keyboardMode.value = 'english';
  }
};

const selectSearchResult = (result: any) => {
  if (!isEditable.value) return;
  //console.log('选择了:', result);

  // 将搜索结果转换为 any 格式
  const newItem: any = {
    name: result.projectName,
    category: activeType.value === '2' ? '检验' : '检查',
    frequency: '',
    cycle: 1,
    subtotalNum:
      result?.price !== undefined && result?.price !== null
        ? '￥' + (Number(result.price) / 100).toFixed(2)
        : '￥' + '0.00',
    frequencyCode: 'qd',
    cycleUnit: 'day',
    cycleUnitText: '天',
    projectId: result.projectId,
    projectName: result.projectName,
    price: result.price,
    priceNum:
      result?.price !== undefined && result?.price !== null
        ? (Number(result.price) / 100).toFixed(2)
        : '0.00',
    projectCategory: result.projectCategory,
    frequencyTimes: frequency.value?.find(
      (freq: { frequencyCode: any }) => freq.frequencyCode === 'qd'
    )?.frequencyTimes,
    projectCategoryName: result.projectCategoryName,
    projectType: result.projectType,
    sampleType: result.sampleType,
    chargeType: result.chargeType,
    unit: result.unit,
    unitName: result.unitName,
    totalOutQty: 1,
    totalOutQtyUnitText: result.unitName,
    totalOutQtyUnit: result.unit,
    subtotal: null,
    uuid: uuidv4(), // 唯一标识
    remark: result.instrs,
  };

  // 通过 emit 更新父组件的数据
  const updatedData = [...displayTableData.value, newItem];
  displayTableData.value = updatedData;
  emit('update:tableData', updatedData);
  ElMessage.success(`已选择: ${result.projectName}`);
  searchKeyboardVisible.value = false;
  searchResults.value = [];
  searchText.value = '';
  emit('search-result-select', result);
};

// 数字键盘相关方法
const showKeyboard = (
  row: any,
  index: number,
  field: 'cycle' | 'totalOutQty'
) => {
  if (!isEditable.value) return;

  currentEditRow.value = row;
  currentEditField.value = field;
  keyboardVisible.value = true;
  searchKeyboardVisible.value = false;
  const _price = Number(row.price) || 0;
  const _qty = Number(row.totalOutQty) || 0;
  // row.subtotal = _price * _qty;
  // row.subtotalNum = '￥' + (row.subtotal / 100).toFixed(2);
  if (row.frequencyTimes && row.cycle && !row.totalOutQty) {
    row.totalOutQty = row.cycle * row.frequencyTimes;
  }
  // 确保字段有初始值
  if (row[field] === undefined || row[field] === null) {
    row[field] = null;
    //console.log('showKeyboard: initialized field value to 1', field);
  }
};

const hideKeyboard = (event?: Event) => {
  if (event && event.target) {
    const target = event.target as Element;
    if (target.closest('.number-keyboard')) {
      return;
    }
  }

  keyboardVisible.value = false;
  currentEditRow.value = null;
  currentEditField.value = null;
};

const inputNumber = (num: string) => {
  //console.log('键盘输入值:', num); // 添加日志输出，显示每次输入的值

  if (!currentEditRow.value || !currentEditField.value) {
    return;
  }

  // 获取当前值，如果不存在则第一次输入直接覆盖
  const currentValue = currentEditRow.value[currentEditField.value];
  let newValue;
  if (currentValue === undefined || currentValue === null) {
    // 第一次输入，直接覆盖
    newValue = parseInt(num);
  } else {
    // 后续输入，拼接
    const currentValueStr = currentValue.toString();
    newValue = parseInt(currentValueStr + num);
  }

  const maxValue = currentEditField.value === 'cycle' ? 999 : 999;

  if (newValue <= maxValue) {
    currentEditRow.value[currentEditField.value] = newValue;
    currentEditRow.value['subtotalNum'] =
      '￥' +
      (
        newValue *
        (currentEditRow.value['price'] / 100) *
        currentEditRow.value['frequencyTimes']
      ).toFixed(2);
    currentEditRow.value['subtotal'] = (
      newValue * currentEditRow.value['price']
    ).toFixed(2);
    if (currentEditField.value == 'cycle') {
      currentEditRow.value['totalOutQty'] =
        newValue * currentEditRow.value['frequencyTimes'];
    }
  } else {
  }
};

const deleteNumber = () => {
  if (!currentEditRow.value || !currentEditField.value) {
    //console.log('deleteNumber: currentEditRow or currentEditField is null');
    return;
  }

  const currentValue = currentEditRow.value[currentEditField.value];
  if (currentValue === undefined || currentValue === null) {
    //console.log('deleteNumber: current value is undefined/null');
    return;
  }

  const currentValueStr = currentValue.toString();
  const newValue = currentValueStr.slice(0, -1);
  currentEditRow.value[currentEditField.value] =
    newValue === '' ? null : parseInt(newValue);
};

const confirmAdd = (row: any, index: number) => {
  if (!row.projectName.trim()) {
    ElMessage.warning('请选择项目');
    return;
  }

  // const newItem: any = {
  //   id: Date.now(),
  //   name: row.name,
  //   category: activeType.value === 'inspection' ? '检验' : '检查',
  //   frequency: row.frequency,
  //   period: row.period,
  //   totalCount: row.totalCount,
  //   remark: row.remark || '新添加项目',
  // };

  // const updatedData = [...props.tableData, newItem];
  // emit('update:tableData', updatedData);
  // ElMessage.success('项目添加成功');
};
// 弹框添加事件
const handleExamineConfirm = (selectedList: any[]) => {
  // 将选中项合并到tableData，避免重复
  //console.log('选中项:', selectedList);

  const existIds = new Set(displayTableData.value.map((item) => item.examId));
  const newItems = selectedList.filter(
    (item) => !existIds.has(item.id || item.examId)
  );
  selectedList.forEach((item) => {
    item.uuid = uuidv4();
    item.cycle = 1;
    item.totalOutQty =
      item?.totalOutQty !== undefined && item?.totalOutQty !== null
        ? item?.totalOutQty
        : '1';
    item.frequencyCode = 'qd';
    item.cycleUnit = 'day';
    item.cycleUnitText = '天';
    item.projectCategoryName = item.projectCategory === '2' ? '检验' : '检查';
    item.category = item.projectCategory;
    item.frequencyTimes = frequency.value?.find(
      (freq: { frequencyCode: any }) => freq.frequencyCode === 'qd'
    )?.frequencyTimes;
    item.priceNum =
      item?.price !== undefined && item?.price !== null
        ? (Number(item.price) / 100).toFixed(2)
        : '0.00';
    item.subtotalNum =
      item?.price !== undefined && item?.price !== null
        ? '￥' + (Number(item.price) / 100).toFixed(2)
        : '￥' + '0.00';
    item.totalOutQtyUnitText = item.unitText;
  });
  displayTableData.value = [...displayTableData.value, ...selectedList];
  const totalCents = displayTableData.value.reduce(
    (acc, cur) =>
      acc + (Number(cur.price) || 0) * (Number(cur.totalOutQty) || 0),
    0
  );
  activeType.value = '';
  TotalCost.value = (totalCents / 100).toFixed(2);
};
// 删除行方法
const deleteRow = (row: any, index: number) => {
  //console.log(displayTableData.value);

  displayTableData.value = displayTableData.value.filter(
    (item) => item.uuid !== row.uuid
  );
  emit('update:tableData', displayTableData.value);
  ElMessage.success('项目删除成功');
};

// 生命周期钩子
onMounted(() => {
  const globalClickHandler = (event: Event) => {
    hideKeyboard(event);
    hideSearchKeyboard(event);
    
  };
  setTimeout(() => {
    document.addEventListener('mousedown', globalClickHandler);
  }, 500);
});

onUnmounted(() => {
  const globalClickHandler = (event: Event) => {
    
    hideKeyboard(event);
    hideSearchKeyboard(event);
  };
  document.removeEventListener('mousedown', globalClickHandler);
});
defineExpose({
  displayTableData,
});
</script>

<style lang="scss" scoped>
::v-deep(.custom-transition-dialog-1) {
  padding: 0 !important;
}
::v-deep(.custom-transition-dialog-1 > .el-dialog__header) {
  padding: 0 !important;
}
.line {
  width: 0px;
  height: 23px;
  border: 1px solid #dcdcdc;
  margin-right: 10px;
}
// 自定义表格样式
.custom-table {
  width: 100%;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  overflow: visible;
  border-radius: 12px 12px 12px 12px;
  position: relative;
  background: #ffffff;
  margin-top: 10px;
  .header-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 10px 20px;

    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
      color: #333;
    }

    .action-buttons {
      display: flex;
      align-items: center;
      .el-button.active {
        background-color: #409eff;
        color: white;
        border-color: #409eff;
      }
    }
  }

  .table-header {
    display: flex;
    background-color: #f5f7fa;
    border-bottom: 1px solid #e4e7ed;

    .header-cell {
      padding: 12px 8px;
      text-align: center;
      font-weight: 600;
      color: #909399;
      font-size: 14px;
      border-right: none;
      align-items: center;
    }
  }

  .table-row-container {
    position: relative;
    display: flex;
    align-items: center;

    &:hover {
      .delete-button-1 {
        opacity: 1;
        visibility: visible;
      }
      /* .delete-button { visibility: visible; } */
    }

    .table-row {
      flex: 1;
      display: flex;
      border-bottom: 1px solid #e4e7ed;

      &:last-child {
        border-bottom: none;
      }

      &:hover {
        background-color: #f5f7fa;
      }

      &.add-row {
        background-color: #fafafa;
      }

      .table-cell {
        padding: 0px 8px;
        align-items: center;
        border-right: none;
        min-height: 50px;
        position: relative;
        display: flex;
        &:last-child {
          justify-content: flex-start;
        }

        &:has(.number-keyboard) {
          overflow: visible;
          z-index: 1;
        }
      }
    }
    .delete-button-1 {
      visibility: hidden;
      opacity: 0;
    }
    .delete-button {
      position: absolute;
      right: -17px;
      top: 50%;
      transform: translateY(-50%);
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #989898;
      border-radius: 50%;
      cursor: pointer;
      // opacity: 0;
      // visibility: hidden;
      transition: all 0.3s ease;
      z-index: 10;

      &:hover {
        transform: translateY(-50%) scale(1.1);
      }

      img {
        width: 16px;
        height: 16px;
        filter: brightness(0) invert(1); // 将图标变为白色
      }
    }
  }

  .table-row {
    display: flex;
  }
}

// 无边框输入框样式
:deep(.borderless-select) {
  .el-input__wrapper {
    border: 1px solid #dcdfe6;
    box-shadow: none;
  }

  &:hover .el-input__wrapper {
    border-color: #c0c4cc;
  }

  &.is-focus .el-input__wrapper {
    border-color: #409eff;
  }
}

:deep(.borderless-input) {
  .el-input__wrapper {
    border: 1px solid #dcdfe6;
    box-shadow: none;
  }

  &:hover .el-input__wrapper {
    border-color: #c0c4cc;
  }

  &.is-focus .el-input__wrapper {
    border-color: #409eff;
  }
}

:deep(.no-border-input) {
  .el-input__wrapper {
    box-shadow: none;
    padding: 0;
  }
}

// 数字键盘样式
.number-keyboard {
  position: absolute;
  top: 60%;
  left: 0;
  z-index: 9999 !important;
  border-radius: 8px;
  padding: 8px;
  margin-top: 4px;
  transform: translateZ(0);

  .keyboard-row {
    display: flex;
    gap: 4px;
    margin-bottom: 4px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .key-btn {
    width: 50px;
    height: 40px;
    border: 1px solid #dcdfe6;
    border-radius: 6px;
    background: #f8f9fa;
    color: #333;
    font-size: 16px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
    display: flex;
    align-items: center;
    justify-content: center;

    &:hover {
      background: #e9ecef;
      border-color: #409eff;
    }

    &:active {
      background: #dee2e6;
      transform: scale(0.95);
    }

    &.delete-btn {
      width: 104px;
      background: #f56c6c;
      color: white;
      font-size: 14px;

      &:hover {
        background: #f78989;
      }
    }
  }
}

// 搜索行样式
.search-row {
  .table-cell {
    border-right: none;

    &:first-child {
      padding-left: 17px;
      display: flex;
      width: 100%;
    }
  }

  .search-input2 {
    :deep(.el-input__wrapper) {
      background-color: transparent;
      box-shadow: none;
      border-radius: 4px;
      height: 50px;
    }

    :deep(.el-input__inner) {
      font-weight: 500;

      &::placeholder {
        font-weight: normal;
      }
    }

    :deep(.el-input__prefix) {
      color: #f87171;
    }
  }
}

// 搜索键盘样式
.search-keyboard {
  position: absolute;
  top: -220px;
  left: 0;
  z-index: 9999;
  background: #f8f9fa;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.25);
  width: 600px;
  max-width: 90vw;

  .keyboard-row {
    display: flex;
    gap: 6px;
    margin-bottom: 8px;
    justify-content: center;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .key-btn {
    min-width: 45px;
    height: 40px;
    border: 1px solid #dcdfe6;
    border-radius: 6px;
    background: #ffffff;
    color: #333;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 8px;

    &:hover {
      background: #e9ecef;
      border-color: #409eff;
    }

    &:active {
      background: #dee2e6;
      transform: scale(0.95);
    }

    &.delete-btn {
      color: rgb(0, 0, 0);
      min-width: 60px;
    }

    &.clear-btn {
      color: rgb(0, 0, 0);
      min-width: 60px;
    }

    &.switch-btn {
      color: rgb(0, 0, 0);
      min-width: 60px;
    }

    &.space-btn {
      min-width: 60px;
      color: rgb(0, 0, 0);
    }
  }
}

// 搜索结果样式
.search-results2 {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  z-index: 9998;
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  margin-top: 4px;
  max-height: 300px;
  overflow-y: auto;
  width: 100%;

  // 重写搜索结果中的表头样式，确保与内容对齐
  .table-header {
    .header-cell {
      text-align: left !important;
      justify-content: flex-start !important;
    }
  }

  .search-result-item {
    display: flex;
    align-items: center;
    border-bottom: 1px solid #f5f7fa;
    cursor: pointer;
    text-align: left;
    transition: background-color 0.2s;
    height: 48px; // 设置固定高度

    &:last-child {
      border-bottom: none;
    }

    &:hover {
      background-color: #f0f9ff;
    }

    // 清除子元素样式，使用内联样式控制
    .result-name,
    .result-category,
    .result-spec,
    .result-price {
      display: flex;
      align-items: center;
      height: 100%;
      font-size: 14px;
      color: #333;
    }

    .result-category,
    .result-spec {
      font-size: 12px;
      color: #000000;
    }

    /* .result-price { font-weight: 600; } */
  }
}
::v-deep(.custom-transition-dialog) {
  padding: 0 !important;
  .el-dialog__header {
    padding: 16px 20px 0 20px;
    border-bottom: none;
  }
  .el-dialog__header {
    display: none;
  }
}
</style>
